import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['Times New Roman']

styles = ['-', '-.', ':', '--', 'solid',
          'dashed', 'dotted', 'dashdot', 'dashed']
markers = [' ', '>', '8', '*', 'x', '+', 'p', 'D']
colors = ["red", "orange", "blue", "c", "cyan",
          "brown", "mediumvioletred", "dodgerblue", "green"]

def load_workload_hour():
    with open('./statistic_result/workload_hour.txt') as f:
        row_list = f.read().splitlines()
    workload_hour_list = []
    for row in row_list:
        workload_hour = row.split('|')
        workload_hour = [float(i) for i in workload_hour]
        workload_hour_list.append(workload_hour)
    return workload_hour_list


def load_a_day_res(filename):
    """
    读取一个结果文件
    """
    with open(filename, 'r') as f:
        row_list = f.read().splitlines()
    a_day_res = row_list[0].split('|')
    a_day_res = [int(float(i)) for i in a_day_res]
    return a_day_res


def make_filename_list(prefix):
    res = []
    for i in range(16, 31):
        res.append(f'{prefix}/energy_{i}_use100_error.txt')
    return res


def make_res_table_statistics(filename_list):
    """
    将某方法结果的所有天跑出来的结果汇总成一个table
    然后得出统计量，提供画图数据
    """
    hour_all = load_workload_hour()
    df_hour_all = np.array(hour_all).reshape(15,24)
   
    tmp = []
    for filename in filename_list:
        tmp.append(load_a_day_res(filename))

    table = pd.DataFrame(tmp) / df_hour_all
    # table = pd.DataFrame(tmp)

    res = np.array(table).flatten()
    return res


def draw_plot(data_dict):
    """
    Input: 接受任意数量的数据，key充当画图的图例，value是画图用的原始数据
    """
    plt.figure(figsize=(10, 4))
    # 适配曲线数量
    count = 0
    for k, data in data_dict.items():
        x = []
        size = len(data)
        for i in range(size):
            x.append(i)
        # plt.bar(x, data, #label=k,
        #          linestyle=styles[count], color=colors[count], linewidth=2.5)

        # sns.lineplot(x, data, label=k, linestyle=styles[count], color=colors[count], linewidth=2.5)
        plt.plot(x, data, label=k, linestyle=styles[count], color=colors[count], linewidth=4)
        count += 1

    # plt.ylim(1000, 5000)
    # plt.xlim(0, 23)
    plt.yticks(fontsize=27)
    plt.xticks(fontsize=27)
    plt.xlabel("Time(h)", fontsize=27)
    plt.ylabel("Workload\nrejection rate", fontsize=25)
    plt.grid()
    plt.legend(fontsize=27, ncol=1, framealpha=0.5)
    return plt


def get_workload_hour_all():
    with open('./statistic_result/workload_hour_all.txt') as f:
        row_list = f.read().splitlines()
    hour_all = row_list[0].split('|')
    hour_all = [float(i) for i in hour_all]
    return hour_all


def get_scheduling_method_data(filename):
    workload_hour_all = np.array(get_workload_hour_all())
    ori_data = np.array(load_a_day_res(filename))
    return ori_data / workload_hour_all
    # return ori_data

if __name__ == "__main__":
    method1 = get_scheduling_method_data('./server_scheduling_final_error/scheduling_method1.txt')[0:168]
    method2 = get_scheduling_method_data('./server_scheduling_final_error/scheduling_method2.txt')[0:168]


    robust_balance_pool_error_list = make_filename_list('./history_compare_error/robust_balance_pool_error')
    robust_balance_pool_error = make_res_table_statistics(robust_balance_pool_error_list)[0:168]


    data_dict = {
        'No-SS': robust_balance_pool_error,
        'SSwithoutSC': method1,
        'SSwithSC': method2,
    }

    pt = draw_plot(data_dict)
    pt.tight_layout()
    file_name = __file__.split('/')[-1].split('.')[0]
    pt.savefig(f"{file_name}.pdf", bbox_inches='tight')
    pt.show()
